"use strict";

import axios from "axios";
import { Message } from 'element-ui'
import store from '@/store/index.js'

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  baseURL: 'http://127.0.0.1:8090'
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
};

export const _axios = axios.create(config);

_axios.interceptors.request.use(
  function(config) {
    // Do something before request is sent
    return config;
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  function(response) {
    // Do something with response data
    return response;
  },
  function(error) {
    // Do something with response error
    return Promise.reject(error);
  }
);

export default _axios;

export const request = (url, method, datum, callback) => {
  const axiosConfig = {
    url: url,
    method: method,
  }

  if (method === 'post') {
    const formData = new FormData()
    for(const key in datum) {
        if (datum[key] instanceof Array) {
            for (const i in datum[key]) {
                formData.append(key, datum[key][i])
            }
        } else {
            formData.append(key, datum[key])
        }
    }
    axiosConfig.data = formData
  } else {
    axiosConfig.params = datum
  }
  store.commit('OPEN_LOADING')

  _axios.request(axiosConfig).then(response => {
    if (response.data.code === 200) {
      if (response.data.message) {
        Message({
          message: response.data.message,
          type: 'success'
        })
      }
      callback(response.data.content)
    } else {
      Message({
        message: response.data.message,
        type: 'error'
      })
    }
  }).catch(error => {
    Message({
      message: error.message,
      type: 'error'
    })
    console.dir(error)
  }).finally(() => {
    store.commit('CLOSE_LOADING')
  })
}

export const get = (url, params, callback) => { request(url, 'get', params, callback) }
export const post = (url, data, callback) => { request(url, 'post', data, callback) }